package com.runvp.task;

import com.runvp.common.enums.EnableStatus;
import com.runvp.common.enums.LineStatus;
import com.runvp.common.utils.DateUtils;
import com.runvp.netty.constant.NettyConstant;
import com.runvp.service.biz.domain.BizDevice;
import com.runvp.service.biz.service.IBizDeviceService;
import com.runvp.service.build.BuildStaticService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class NettyServerTask {



    @Autowired
    private IBizDeviceService bizDeviceService;
    /**
     * 第三分钟开始，2分钟执行一次
     * 3 定时清理通道信息
     */
    @Async
//    @Scheduled(fixedRate = 60000)
    @Scheduled(cron = "0 3/2 * * * ?")
    public synchronized void refreshChannel() {
        exeRefreshChannel();
    }

    /**
     * 执行刷新
     */
    public synchronized void exeRefreshChannel(){
        String enableClearChanel = BuildStaticService.configService.selectConfigByKey("enableClearChanel");
        log.info("定时清理通开关enableClearChanel:【{}】",enableClearChanel);
        if(StringUtils.isBlank(enableClearChanel) || !EnableStatus.ENABLE.getCode().equals(enableClearChanel)){
            log.warn("未开启清理通道,执行结束");
            return;
        }
        long st = System.currentTimeMillis();
        log.info("清理通道开始时间:【{}】 ", DateUtils.now());
        //移除心跳周期内未活跃的设备
        BizDevice query = new BizDevice();
        query.setLineStatus(LineStatus.ON_LINE.getCode());
        List<BizDevice> deviceList = bizDeviceService.selectBizDeviceList(query);
        if(!CollectionUtils.isEmpty(deviceList)){
            List<String> deviceSns = deviceList.stream().map(BizDevice::getDeviceCode).collect(Collectors.toList());
            NettyConstant.allOnlineChannleIds.entrySet().removeIf(map -> !deviceSns.contains(map.getValue()));
        }
        //清理错误通道
        NettyConstant.removeErrorChannel();
        log.info("清理通道结束时间: 【{}】 ,用时：【{}】", DateUtils.now(), (System.currentTimeMillis() - st) + " ms");
    }

}
